package com.fis.mca;

import java.util.HashMap;
import java.util.Vector;

import org.vaadin.dialogs.ConfirmDialog;
import org.vaadin.dialogs.DefaultConfirmDialogFactory;

import com.fis.mca.admin.AppClient;
import com.fis.vaadin.component.DialogChangePassword;
import com.fis.vaadin.component.PanelStatusBar;
import com.fis.vaadin.component.TreeTabPanel;
import com.fis.vaadin.util.FormUtil;
import com.fss.ddtp.DDTP;
import com.vaadin.data.Property;
import com.vaadin.data.Property.ValueChangeEvent;
import com.vaadin.terminal.ThemeResource;
import com.vaadin.ui.Alignment;
import com.vaadin.ui.Button;
import com.vaadin.ui.CssLayout;
import com.vaadin.ui.CustomLayout;
import com.vaadin.ui.HorizontalLayout;
import com.vaadin.ui.MenuBar;
import com.vaadin.ui.MenuBar.Command;
import com.vaadin.ui.MenuBar.MenuItem;
import com.vaadin.ui.Panel;
import com.vaadin.ui.VerticalLayout;

import eu.livotov.tpt.i18n.TM;

public class MainWindow extends VerticalLayout implements
		Property.ValueChangeListener {
	private HashMap<MenuBar.MenuItem, Class<?>> menuTable;

	// private VerticalLayout this;
	private Panel pnlMainDisplay;
	private MenuBar menubar;
	private MenuBar menubarRight;
	private PanelStatusBar pnlStatus;
	// private MenuBar lblLoginName;
	private MenuItem mniFormCaption;

	private TreeTabPanel centerPanel;

	public MainWindow() {
		// super("MCA Web Application");
		// this = (VerticalLayout) this.getContent();
		this.setMargin(false);
		menuTable = new HashMap<MenuBar.MenuItem, Class<?>>();
		initLayout();
	}

	private void initLayout() {
		this.setSizeFull();

		CssLayout banner = new CssLayout();
		banner.setStyleName("toolbar");
		banner.setWidth("100%");
		banner.setHeight("76px");

		CustomLayout custom = new CustomLayout("banner");
		custom.setSizeFull();
		banner.addComponent(custom);

		this.addComponent(banner);

		// HorizontalLayout hl = createToolbar();
		MenuBar menu = getTopMenu();
		HorizontalLayout hLayout = new HorizontalLayout();
		hLayout.setWidth("100%");
		hLayout.addComponent(menu);
		this.addComponent(hLayout);

		menubarRight = new MenuBar();
		menubarRight.setSizeFull();
		menubarRight.setStyleName("menubarRight");
		hLayout.addComponent(menubarRight);
		hLayout.setComponentAlignment(menubarRight, Alignment.TOP_RIGHT);

		hLayout.setExpandRatio(menu, 1);
		hLayout.setExpandRatio(menubarRight, 1);

		pnlMainDisplay = new Panel();
		pnlMainDisplay.setStyleName("mca-panel-caption");
		pnlMainDisplay.setSizeFull();

		// ////////////////////////////////////
		// HorizontalSplitPanel centerPanel = new HorizontalSplitPanel();
		// tree = new DecoratedTree();
		// ComboBox cboSearch = new ComboBox();
		// PanelTreeProvider treeprovider = new PanelTreeProvider()
		// {
		//
		// @Override
		// public void treeValueChanged(Object obj)
		// {
		// if (tree.areChildrenAllowed(obj))
		// {
		// System.out.println(obj);
		// }
		// else
		// {
		// Class<ComponentContainer> cl;
		// try
		// {
		// cl = (Class<ComponentContainer>) Class.forName(obj.toString());
		// ComponentContainer instance = cl.newInstance();
		// showForm(instance);
		// }
		// catch (ClassNotFoundException ex)
		// {
		// // TODO Auto-generated catch block
		// ex.printStackTrace();
		// }
		// catch (InstantiationException ex)
		// {
		// // TODO Auto-generated catch block
		// ex.printStackTrace();
		// }
		// catch (IllegalAccessException ex)
		// {
		// // TODO Auto-generated catch block
		// ex.printStackTrace();
		// }
		// }
		// }
		//
		// @Override
		// public void filterTree(Object obj)
		// {
		// System.out.println(obj);
		// }
		// };
		// CommonTreePanel treePanel = new CommonTreePanel(tree, cboSearch,
		// treeprovider);
		// centerPanel.setSplitPosition(250, Sizeable.UNITS_PIXELS);
		// centerPanel.setFirstComponent(treePanel);
		// centerPanel.setSecondComponent(pnlMainDisplay);
		// /////////////////////////////////////////

		initCenterPanel();
		pnlMainDisplay.setContent(centerPanel);
		this.addComponent(pnlMainDisplay);
		this.setExpandRatio(pnlMainDisplay, 1);

		// this.addComponent(centerPanel);
		// this.setExpandRatio(centerPanel, 1);

		pnlStatus = new PanelStatusBar();
		this.addComponent(pnlStatus);

		ConfirmDialog.Factory df = new DefaultConfirmDialogFactory() {

			// We change the default order of the buttons
			@Override
			public ConfirmDialog create(String caption, String message,
					String okCaption, String cancelCaption) {
				ConfirmDialog d = super.create(caption, message, okCaption,
						cancelCaption);

				// Change the order of buttons
				Button ok = d.getOkButton();
				HorizontalLayout buttons = (HorizontalLayout) ok.getParent();
				buttons.removeComponent(ok);
				buttons.addComponent(ok, 1);
				buttons.setComponentAlignment(ok, Alignment.MIDDLE_RIGHT);

				return d;
			}

		};
		ConfirmDialog.setFactory(df);
	}

	private void initCenterPanel() {
		centerPanel = new TreeTabPanel();
		// centerPanel.addTreeValueChangeListener(this);
	}

	private MenuBar getTopMenu() {

		menubar = new MenuBar();
		menubar.setWidth("100%");

		return menubar;
	}

	public void initComponent() {
		if (AppClient.getLoginStatus()) {
			try {
				DDTP request = new DDTP();
				request.setString("strApp", "3"); // app_id = 3: Admin
				DDTP response = AppClient.sendRequest("PermissionBean",
						"queryMenuData", request);
				Vector vt = (Vector) response.getReturn();

				// loadMenu(menubar,vt);
				centerPanel.buildTree(vt);
				loadMenuBar();

				// ModuleManager.buildMenuBar(menubar, vt);
				// ModuleManager.buildTree(tree, null, vt);

				// MenuBar.MenuItem item =
				// ModuleManager.getMenuItem("MCA.System");
				// item.addSeparator();
				// item.addItem("Exit", null);

				// System.out.println("total: " + vt.size());
			} catch (Exception ex) {
				ex.printStackTrace();
			}
		}
	}

	private void loadMenuBar() {
		MenuBar.MenuItem item = menubar.addItem("More options",
				new ThemeResource("icons/16/system.png"), null);
		// item.addItem("Log in", new ThemeResource("icons/16/login.png"),
		// new Command() {
		//
		// @Override
		// public void menuSelected(MenuItem selectedItem) {
		// logout();
		// }
		// });
		item.addItem("Change password", new ThemeResource(
				"icons/16/changepassword.png"), new Command() {
			@Override
			public void menuSelected(MenuItem selectedItem) {
				openChangePasswordDialog();
			}
		});
		item.addSeparator();
		item.addItem("Log out", new ThemeResource("icons/16/logout.png"),
				new Command() {

					@Override
					public void menuSelected(MenuItem selectedItem) {
						logout();
					}
				});
	}

	// private void loadMenu(Object menu, Vector vtMenu)
	// {
	// for(int iIndex = 0;iIndex < vtMenu.size();iIndex++)
	// {
	// Vector vtInfo = (Vector)vtMenu.elementAt(iIndex);
	// String strMenuName = StringUtil.nvl(vtInfo.elementAt(1),"");
	// String strMenuType = StringUtil.nvl(vtInfo.elementAt(2),"");
	// // Component cmp = findMenu((JComponent)cmpParent,strMenuName);
	// if(strMenuType.equals("G"))
	// {
	// if (menu.equals(menubar))
	// {
	// MenuBar.MenuItem item = menubar.addItem(strMenuName, null);
	// loadMenu(item, (Vector)vtInfo.elementAt(3));
	// }
	// else
	// {
	// MenuBar.MenuItem item = ((MenuBar.MenuItem)menu).addItem(strMenuName,
	// null);
	// loadMenu(item, (Vector)vtInfo.elementAt(3));
	// }
	// }
	// else if(strMenuType.equals("M"))
	// {
	// if (menu.equals(menubar))
	// {
	// MenuBar.MenuItem item = menubar.addItem(TM.get(strMenuName), new
	// ShowFormCommand(strMenuName));
	// item.setEnabled(AppClient.getPermission(strMenuName).contains("S"));
	// // loadMenu(item, (Vector)vtInfo.elementAt(3));
	// }
	// else
	// {
	// MenuBar.MenuItem item =
	// ((MenuBar.MenuItem)menu).addItem(TM.get(strMenuName), new
	// ShowFormCommand(strMenuName));
	// item.setEnabled(AppClient.getPermission(strMenuName).contains("S"));
	// // loadMenu(item, (Vector)vtInfo.elementAt(3));
	// }
	// }
	// else if(strMenuType.equals("S"))
	// {
	// ((MenuBar.MenuItem)menu).addSeparator();
	// }
	// }
	// }

	void clearCache() {
		FormUtil.clearCache(getWindow());
		// System.out.println("cached cleared: " + CacheDB.cacheService.size());
		// CacheDB.cacheService.clear();
		// CacheDB.cacheAction.clear();
		// CacheDB.cachePackage.clear();
		// getWindow().showNotification("XÃ³a cache thÃ nh cÃ´ng!");
		// System.out.println("size: " + CacheDB.cacheService.size());
	}

	public String getPermission(Class module) {
		// System.out.println(module.getName());
	
		return AppClient.getPermission(module.getName());
	}

	public void setUsernameCaption(String caption) {
		mniFormCaption = menubarRight.addItem(
				TM.get("main.menubar.login.caption") + " " + caption, null);
		mniFormCaption.setStyleName("form-caption");
	}

	// private class ShowFormCommand implements MenuBar.Command
	// {
	// private String className;
	// ShowFormCommand(String className)
	// {
	// this.className = className;
	// }
	//
	// @Override
	// public void menuSelected(MenuItem selectedItem)
	// {
	// try
	// {
	// Class<ComponentContainer> obj = (Class<ComponentContainer>)
	// Class.forName(className);
	// ComponentContainer instance = obj.newInstance();
	// showForm(instance);
	// }
	// catch (ClassNotFoundException ex)
	// {
	// // TODO Auto-generated catch block
	// ex.printStackTrace();
	// }
	// catch (InstantiationException ex)
	// {
	// // TODO Auto-generated catch block
	// ex.printStackTrace();
	// }
	// catch (IllegalAccessException ex)
	// {
	// // TODO Auto-generated catch block
	// ex.printStackTrace();
	// }
	//
	// }
	//
	// }

	/*
	 * private void showForm(ComponentContainer form) { //
	 * pnlMainDisplay.removeAllComponents();
	 * pnlStatus.setFormCaption(form.getCaption()); form.setCaption(null);
	 * form.setSizeFull(); pnlMainDisplay.setContent(form); //
	 * pnlMainDisplay.setCaption(form.getCaption());
	 * 
	 * }
	 */
	public void updateLanguage() {
		pnlStatus.updateLanguage();
	}

	/*
	 * private ComponentContainer createForm(String className) { try {
	 * Class<ComponentContainer> obj = (Class<ComponentContainer>)
	 * Class.forName(className); ComponentContainer instance =
	 * obj.newInstance();
	 * 
	 * return instance; } catch (ClassNotFoundException ex) { // TODO
	 * Auto-generated catch block ex.printStackTrace(); } catch
	 * (InstantiationException ex) { // TODO Auto-generated catch block
	 * ex.printStackTrace(); } catch (IllegalAccessException ex) { // TODO
	 * Auto-generated catch block ex.printStackTrace(); }
	 * 
	 * return null; }
	 */

	@Override
	public void valueChange(ValueChangeEvent event) {
		// Object value = event.getProperty().getValue();
		//
		// if (value instanceof TreeItemId)
		// {
		// try
		// {
		// TreeItemId id = (TreeItemId) value;
		// centerPanel.addTab(id.getRelatedForm());
		// }
		// catch (InstantiationException ex)
		// {
		// ex.printStackTrace();
		// MessageAlerter.showErrorMessage(getWindow(), ex.getMessage());
		// }
		// catch (IllegalAccessException ex)
		// {
		// ex.printStackTrace();
		// MessageAlerter.showErrorMessage(getWindow(), ex.getMessage());
		// }
		// catch (ClassNotFoundException ex)
		// {
		// ex.printStackTrace();
		// MessageAlerter.showErrorMessage(getWindow(), ex.getMessage());
		// }
		// }
	}

	private void openChangePasswordDialog() {
		DialogChangePassword changePassword = new DialogChangePassword();
		getWindow().addWindow(changePassword);
	}

	private void logout() {
		ConfirmDialog.show(getWindow(), TM.get("logout.confirm.title"),
				TM.get("logout.confirm.description"), "Yes", "No",
				new ConfirmDialog.Listener() {
					public void onClose(ConfirmDialog dialog) {

						if (dialog.isConfirmed()) {
							getApplication().setUser(null);
							getApplication().close();
							clearCache();
						}
					}
				});
	}

}
